package com.kaiwukj.android.ufamily.mvp.ui.page.home.home;

import android.graphics.Color;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.ctetin.expandabletextviewlibrary.ExpandableTextView;
import com.ctetin.expandabletextviewlibrary.app.StatusType;
import com.kaiwukj.android.mcas.http.imageloader.glide.GlideArms;
import com.kaiwukj.android.mcas.utils.McaUtils;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.MyApplication;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.app.constant.Constant;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.CommentResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.CommunityInfoResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.CommunityNewResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.DynamicResult;
import com.kaiwukj.android.ufamily.mvp.ui.adapter.NineGridIvAdapter;
import com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.SocialCircleActivity;
import com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.detail.DynamicDetailFragment;
import com.kaiwukj.android.ufamily.mvp.ui.page.home.FriendRecommendAdapter;
import com.kaiwukj.android.ufamily.mvp.ui.page.service.community.CommunityServiceWebActivity;
import com.kaiwukj.android.ufamily.mvp.ui.widget.SpaceItemDecoration;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.NineGridView;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

import org.jetbrains.annotations.NotNull;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class HomeAdapter extends BaseMultiItemQuickAdapter<HomeMultiItemEntity, BaseViewHolder> {

    private ActiveHotAdapter mActiveAdapter;
    //private DynamicAdapter mDynamicAdapter;
    private FriendRecommendAdapter mFriendAdapter;
    private RecoFriendChildAdapter mRecoFriendChildAdapter;

    public HomeAdapter(List<HomeMultiItemEntity> data) {
        super(data);
        addItemType(HomeMultiItemEntity.HOME_BANNER, R.layout.item_home_banner);
        //addItemType(HomeMultiItemEntity.HOME_NOTICE, R.layout.item_home_notice);
        addItemType(HomeMultiItemEntity.HOME_FRIEND_RECOMMEND, R.layout.item_home_active);
        addItemType(HomeMultiItemEntity.HOME_FRIEND_RECOMMEND_BETA, R.layout.item_home_attention_friend);
        addItemType(HomeMultiItemEntity.HOME_ACTIVE, R.layout.item_home_active);
        addItemType(HomeMultiItemEntity.HOME_DYNAMIC, R.layout.item_dynamic);
        addItemType(HomeMultiItemEntity.HOME_COMMUNITY_NEWS, R.layout.item_home_news);
        addChildClickViewIds(R.id.iv_close);

    }

    public HomeAdapter() {
        this(new ArrayList<>());
    }

    public int getChildItemCount() {
        int activeCount = mActiveAdapter == null ? 0 : mActiveAdapter.getItemCount();
        //  int dynamicCount = mDynamicAdapter == null ? 0 : mDynamicAdapter.getItemCount();
        int friendCount = mFriendAdapter == null ? 0 : mFriendAdapter.getItemCount();
        return activeCount + friendCount;
    }

    public FriendRecommendAdapter getFriendAdapter() {
        return mFriendAdapter;
    }

    public RecoFriendChildAdapter getRecoFriendAdapter() {
        return mRecoFriendChildAdapter;
    }

    public void removeItemByFlag(int flag) {
        for (int i = 0; i < getData().size(); i++) {
            if (flag == getData().get(i).getItemType()) {
                removeAt(i);
            }
        }
    }

    public DynamicResult getDynamicByPosition(int position) {
        if (getItem(position).getItemType() == HomeMultiItemEntity.HOME_DYNAMIC) {
            return getItem(position).getDynamicResult();
        }
        return null;
    }

    @Override
    protected void convert(@NotNull BaseViewHolder holder, HomeMultiItemEntity item, @NotNull List<?> payloads) {
//        LogUtils.d("payloads------------------->" + GsonUtils.toJson(payloads));
        if (payloads.isEmpty()) {
            super.convert(holder, item, payloads);
        } else {
            switch (item.getItemType()) {
                case HomeMultiItemEntity.HOME_DYNAMIC:
                    String tag = (String) payloads.get(0);
                    DynamicResult dynamicResult = item.getDynamicResult();
                    if ("postLike".equals(tag)) {
                        //ImageView ivGood = holder.getView(R.id.iv_good);
                        if (dynamicResult.isPraise()) {
                            holder.setImageResource(R.id.iv_good, R.mipmap.ic_dynamic_good_checked);
                        } else {
                            holder.setImageResource(R.id.iv_good, R.mipmap.ic_dynamic_good);
                        }
                        //tvGoodNum.setText(String.valueOf(getItem(position).getThumbNumText()));
                        holder.setText(R.id.tv_good_num, dynamicResult.getThumbNumText());
                    } else if ("postComment".equals(tag)) {
                        holder.setText(R.id.tv_comment_num, dynamicResult.getCommentNumText());
                    } else if ("postAttention".equals(tag)) {
                        holder.setVisible(R.id.btn_attention, !dynamicResult.isAttention());
                    }
                    break;
                default:
                    convert(holder, item);
            }
        }
    }

    @Override
    protected void convert(@NotNull BaseViewHolder helper, HomeMultiItemEntity item) {
        switch (item.getItemType()) {
            case HomeMultiItemEntity.HOME_BANNER:
                CommunityInfoResult infoResult = item.getCommunityInfo();
                helper.setText(R.id.tv_total_area, String.format("社区面积：%s平方米", infoResult.getCommunityArea()));
                helper.setText(R.id.tv_build_area, String.format("%s", infoResult.getBuildArea()));
                double to = 0;
                if (infoResult.getGreenArea() > 0 && infoResult.getCommunityArea() > 0) {
                    to = infoResult.getGreenArea() / infoResult.getCommunityArea();
                    DecimalFormat df = new DecimalFormat("#.##");
                    helper.setText(R.id.tv_green_area, df.format(to * 100));

                } else {
                    helper.setText(R.id.tv_green_area, "0");
                }


                helper.setText(R.id.tv_other_area, String.format("%s", infoResult.getOtherArea()));
                break;
            case HomeMultiItemEntity.HOME_NOTICE:
                helper.setText(R.id.tv_text, item.getNotice().getTitle());
                //helper.getView(R.id.iv_close).setOnClickListener(v -> removeAt(helper.getAdapterPosition()));
                helper.itemView.setOnClickListener(v -> {
                    ARouter.getInstance().build(ARouterUrlKt.CommunityNoticeUrl)
                            .withString("EXTRA_KEY_FRAGMENT", "detail")
                            .withSerializable("result", item.getNotice())
                            .navigation();
                });
                break;
            case HomeMultiItemEntity.HOME_ACTIVE:
                helper.getView(R.id.tv_more).setOnClickListener(v -> {
                    if (mEvent != null) {
                        mEvent.onActiveMore();
                    }
                });
                helper.setText(R.id.tv_active_title, "热门活动");
                RecyclerView mActiveRv = helper.getView(R.id.recycler);
                mActiveRv.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
                SpaceItemDecoration spaceItemDecoration = new SpaceItemDecoration(10, RecyclerView.HORIZONTAL);
                if (mActiveRv.getItemDecorationCount() == 0) {
                    mActiveRv.addItemDecoration(spaceItemDecoration);
                }
                mActiveAdapter = new ActiveHotAdapter(item.getActives());
                mActiveRv.setAdapter(mActiveAdapter);
                mActiveAdapter.setOnItemClickListener((adapter, view, position) -> {
                    //跳转活动详情
                    ARouter.getInstance().build(ARouterUrlKt.EventDetail)
                            .withInt("id", (int) adapter.getItemId(position))
                            .navigation();
                });
                mActiveAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                    if (view.getId() == R.id.btn_submit) {
                        //跳转活动详情
                        ARouter.getInstance().build(ARouterUrlKt.EventDetail)
                                .withInt("id", (int) adapter.getItemId(position))
                                .navigation();
                    } else if (view.getId() == R.id.btn_join) {
                        ARouter.getInstance().build(ARouterUrlKt.EventDetail)
                                .withInt("id", (int) adapter.getItemId(position))
                                .navigation();
                    }
                });

                break;
            case HomeMultiItemEntity.HOME_FRIEND_RECOMMEND:
                helper.setVisible(R.id.tv_more, false);
                helper.setText(R.id.tv_active_title, "推荐关注");
                mFriendAdapter = new FriendRecommendAdapter(item.getFriendList());
                RecyclerView mFriendRv = helper.getView(R.id.recycler);
                mFriendRv.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
                if (mFriendRv.getItemDecorationCount() == 0) {
                    mFriendRv.addItemDecoration(new SpaceItemDecoration(10, RecyclerView.HORIZONTAL));
                }
                mFriendRv.setAdapter(mFriendAdapter);
                mFriendAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                    if (mEvent != null)
                        mEvent.onAttention(mFriendAdapter.getItem(position).getUserId(), position);
                });
                mFriendAdapter.setOnItemClickListener((adapter, view, position) ->
                        ARouter.getInstance().build(ARouterUrlKt.DynamicPersonUrl)
                                .withInt("userId", mFriendAdapter.getItem(position).getUserId())
                                .navigation());
                break;
            case HomeMultiItemEntity.HOME_FRIEND_RECOMMEND_BETA:
                helper.getView(R.id.btn_refresh).setOnClickListener(v -> {
                    if (mEvent != null) {
                        mEvent.onRefreshFriend();
                    }
                });
                RecyclerView rvRecoChildList = helper.getView(R.id.rv_base);
                rvRecoChildList.setLayoutManager(new LinearLayoutManager(getContext()));
                mRecoFriendChildAdapter = new RecoFriendChildAdapter(item.getFriendList());
                rvRecoChildList.setAdapter(mRecoFriendChildAdapter);
                mRecoFriendChildAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                    if (mEvent != null)
                        mEvent.onAttention(mRecoFriendChildAdapter.getItem(position).getUserId(), position);
                });
                mRecoFriendChildAdapter.setOnItemClickListener((adapter, view, position) ->
                        ARouter.getInstance().build(ARouterUrlKt.DynamicPersonUrl)
                                .withInt("userId", mRecoFriendChildAdapter.getItem(position).getUserId())
                                .navigation());
                mRecoFriendChildAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                    if (view.getId() == R.id.btn_attention) {
                        if (mEvent != null) {
                            mEvent.onAttention(mRecoFriendChildAdapter.getItem(position).getUserId(), position);
                        }
                    }
                });
                break;
            case HomeMultiItemEntity.HOME_DYNAMIC:
                bindDynamic(helper, item.getDynamicResult());
               /* RecyclerView mDynamicRv = helper.getView(R.id.rv_base);
                mDynamicRv.setLayoutManager(new LinearLayoutManager(getContext()));
                if (mDynamicRv.getItemDecorationCount() == 0) {
                    mDynamicRv.addItemDecoration(new RecycleViewDivide(LinearLayoutManager.VERTICAL,
                            null, 10,
                            ContextCompat.getColor(getContext(), R.color.window_background_color)));
                }
                DynamicAdapter mDynamicAdapter = new DynamicAdapter(item.getDynamicList());
                mDynamicRv.setAdapter(mDynamicAdapter);
                mDynamicAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                    switch (view.getId()) {
                        case R.id.container_good:
                            DynamicResult result = mDynamicAdapter.getItem(position);
                            if (result.isPraise()) {
                                if (mEvent != null)
                                    mEvent.onPostCancelLike(helper.getAdapterPosition(), position);

                            } else {
                                if (mEvent != null)
                                    mEvent.onPostLike(helper.getAdapterPosition(), position);
                            }
                            break;
                        case R.id.container_comment:
                            if (mEvent != null)
                                mEvent.onComment(helper.getAdapterPosition(), position);
                            break;
                        case R.id.container_action_more:
                            if (mEvent != null)
                                mEvent.onMoreEvent(helper.getAdapterPosition(), position);
                            break;
                        case R.id.btn_attention:
                            if (mEvent != null) {
                                mEvent.onAttentionById(mDynamicAdapter.getItem(position).getUserId());
                                view.setVisibility(View.GONE);
                            }
                            break;
                    }
                });*/
                break;
            case HomeMultiItemEntity.HOME_COMMUNITY_NEWS:
                helper.getView(R.id.tv_more).setOnClickListener(v ->
                        ARouter.getInstance().build(ARouterUrlKt.CommunityNewsUrl).navigation());
                List<CommunityNewResult> newsList = item.getCommunityNews();
                if (newsList.size() >= 1) {
                    helper.setText(R.id.tv_title, newsList.get(0).getArticleTitle());
                    helper.setText(R.id.tv_time, TimeUtils.getFriendlyTimeSpanByNow(newsList.get(0).getCreateTime()));
                    Glide.with(getContext())
                            .load(newsList.get(0).getThumbnail())
                            .placeholder(R.drawable.picture_image_placeholder)
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .into((ImageView) helper.getView(R.id.image_01));
                    helper.getView(R.id.image_01).setOnClickListener(v ->
                            ARouter.getInstance().build(ARouterUrlKt.CommunityServiceWeb)
                                    .withInt("articleId", newsList.get(0).getId())
                                    .withInt("type", CommunityServiceWebActivity.NEWS)
                                    .withString("url", Constant.SERVICE_COMMUNITY_NEWS)
                                    .navigation());

                }
                if (newsList.size() >= 2) {
                    helper.setText(R.id.tv_title_02, newsList.get(1).getArticleTitle());
                    helper.setVisible(R.id.tv_title_02, true);
                    helper.setVisible(R.id.image02, true);
                    Glide.with(getContext())
                            .load(newsList.get(1).getThumbnail())
                            .placeholder(R.drawable.picture_image_placeholder)
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .into((ImageView) helper.getView(R.id.image02));
                    helper.getView(R.id.image02).setOnClickListener(v ->
                            ARouter.getInstance().build(ARouterUrlKt.CommunityServiceWeb)
                                    .withInt("articleId", newsList.get(1).getId())
                                    .withInt("type", CommunityServiceWebActivity.NEWS)
                                    .withString("url", Constant.SERVICE_COMMUNITY_NEWS)
                                    .navigation());
                } else {
                    helper.setVisible(R.id.tv_title_02, false);
                    helper.setVisible(R.id.tv_title_03, false);
                    helper.setVisible(R.id.image02, false);
                    helper.setVisible(R.id.image03, false);
                }

                if (newsList.size() >= 3) {
                    helper.setText(R.id.tv_title_03, newsList.get(2).getArticleTitle());
                    helper.setVisible(R.id.tv_title_03, true);
                    helper.setVisible(R.id.image03, true);
                    Glide.with(getContext())
                            .load(newsList.get(2).getThumbnail())
                            .placeholder(R.drawable.picture_image_placeholder)
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .into((ImageView) helper.getView(R.id.image03));
                    helper.getView(R.id.image03).setOnClickListener(v ->
                            ARouter.getInstance().build(ARouterUrlKt.CommunityServiceWeb)
                                    .withInt("articleId", newsList.get(2).getId())
                                    .withInt("type", CommunityServiceWebActivity.NEWS)
                                    .withString("url", Constant.SERVICE_COMMUNITY_NEWS)
                                    .navigation());

                } else {
                    helper.setVisible(R.id.tv_title_03, false);
                    helper.setVisible(R.id.image03, false);
                }
                break;
        }
    }

    public void postJoin(int id, boolean join) {
        if (mActiveAdapter == null) return;
        mActiveAdapter.postJoin(mActiveAdapter.getPositionById(id), join);
    }


    public void addDynamic(List<DynamicResult> list, boolean isLoadingMore) {
        /*if (mDynamicAdapter == null) {
            return;
        }*/
        List<HomeMultiItemEntity> mData = new ArrayList<>();
        for (DynamicResult result : list) {
            HomeMultiItemEntity entity = new HomeMultiItemEntity(HomeMultiItemEntity.HOME_DYNAMIC);
            entity.setDynamicResult(result);
            mData.add(entity);
        }
        if (isLoadingMore) {
            addData(mData);
            //  mDynamicAdapter.addData(list);
        } else {
            setNewInstance(mData);
            //mDynamicAdapter.setList(list);
        }
    }

    public void delDynamic(int position) {
        /*if (mDynamicAdapter != null) {
            mDynamicAdapter.removeAt(childPos);
        }*/
        if (getItemViewType(position) == HomeMultiItemEntity.HOME_DYNAMIC) {
            removeAt(position);
        }
    }


    private void bindDynamic(BaseViewHolder helper, DynamicResult item) {

        ImageView ivGood = helper.getView(R.id.iv_good);
        if (item.isPraise()) {
            ivGood.setImageResource(R.mipmap.ic_dynamic_good_checked);
        } else {
            ivGood.setImageResource(R.mipmap.ic_dynamic_good);
        }

        //Placeholder placeholder = helper.getView(R.id.place_holder);
        helper.setVisible(R.id.btn_attention, !item.isAttention() && !item.getUserId().equals(MyApplication.getInstance().getUserInfo().getId()));
        QMUIRoundButton btnTag = helper.getView(R.id.tag);

        // addChildClickViewIds(R.id.iv_avatar, R.id.iv_video_play);

        helper.itemView.setOnClickListener(v ->
                ARouter.getInstance().build(ARouterUrlKt.SocialCircleUrl)
                        .withString(SocialCircleActivity.FRAGMENT_KEY, DynamicDetailFragment.CIRCLE_CARD_DETAIL)
                        //.withSerializable(SocialCircleActivity.FRAGMENT_KEY_CARD_BEAN, item)
                        .withInt("dynamicId", item.getId())
                        // .withInt("itemPos", helper.getAdapterPosition())
                        .navigation());
        helper.getView(R.id.iv_avatar).setOnClickListener(v ->
                ARouter.getInstance().build(ARouterUrlKt.DynamicPersonUrl)
                        .withInt("userId", item.getUserId())
                        .navigation());

        ViewGroup cagGroup = helper.getView(R.id.container_group_cag);


        /*if (index == 1) {
            //  placeholder.setContentId(R.id.container_group_cag);
            btnTag.setVisibility(View.GONE);
        } else {*/
        btnTag.setOnClickListener(v -> ARouter.getInstance()
                .build(ARouterUrlKt.TopicIndexUrl)
                .withInt("topicId", item.getTopicId())
                .navigation());
        //    }

        if (StringUtils.isEmpty(item.getTopicTitle())) {
            btnTag.setVisibility(View.GONE);
        } else {
            btnTag.setVisibility(View.VISIBLE);
        }

        Glide.with(getContext())
                .load(item.getHeadImg())
                .into((ImageView) helper.getView(R.id.iv_avatar));

        helper.setText(R.id.tv_user_name, item.getUserName());
        String publishTime = TimeUtils.getFriendlyTimeSpanByNow(item.getCreateTime());
        String communityName = item.getCommunityName();
        SpannableString spanString = new SpannableString(String.format("%s 来自%s", publishTime, communityName));
        spanString.setSpan(new ForegroundColorSpan(Color.parseColor("#3A82C4")),
                spanString.length() - communityName.length(), spanString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        helper.setText(R.id.tv_user_community, spanString);
        //helper.setText(R.id.tv_note, item.getDynamicContent());
        ExpandableTextView tvNote = helper.getView(R.id.tv_note);
        tvNote.setContent(item.getDynamicContent());
        tvNote.setExpandOrContractClickListener(type -> {
            if (type == StatusType.STATUS_CONTRACT) {
                if (mEvent != null) {
                    mEvent.onDynamicContract(helper.getAdapterPosition());
                    //  helper.getLayoutPosition()
                }
            }
        });
        helper.setText(R.id.tag, item.getTopicTitle());
        helper.setText(R.id.tv_comment_num, item.getCommentNumText());
        helper.setText(R.id.tv_good_num, item.getThumbNumText());

        ViewGroup containerMedia = helper.getView(R.id.container_media);
        NineGridView containerImage = helper.getView(R.id.container_image);
        ViewGroup containerVideo = helper.getView(R.id.container_video);

        helper.getView(R.id.container_good).setOnClickListener(v -> {
            if (mEvent != null) {
                if (item.isPraise()) {
                    mEvent.onPostCancelLike(item.getId(), helper.getAdapterPosition());
                } else {
                    mEvent.onPostLike(item.getId(), helper.getAdapterPosition());
                }
            }
        });

        helper.getView(R.id.view_comment).setOnClickListener(v -> {
            if (mEvent != null) {
                mEvent.onComment(item.getId(), helper.getAdapterPosition());
            }
        });

        helper.getView(R.id.btn_attention).setOnClickListener(v -> {
            if (mEvent != null) {
                v.setVisibility(View.GONE);
                mEvent.onAttention(item.getUserId(), helper.getAdapterPosition());
            }
        });

        helper.getView(R.id.container_action_more).setOnClickListener(v -> {
            if (mEvent != null) {
                mEvent.onMoreEvent(item.getId(), helper.getAdapterPosition(), item.getUserId());
            }
        });

        if (StringUtils.isEmpty(item.getImages()) && StringUtils.isEmpty(item.getVideo())) {
            containerMedia.setVisibility(View.GONE);
        } else {
            containerMedia.setVisibility(View.VISIBLE);
            if (!StringUtils.isEmpty(item.getVideo())) {
                //91360111MA38CD9D4M
                //江西省开物科技有限公司
                //  LogUtils.d("url------------->" + item.getImage());
                //存在视频
                ImageView ivVideoCover = helper.getView(R.id.iv_video_cover);
                GlideArms.with(getContext())
                        .load(item.getImages())
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(ivVideoCover);
                containerImage.setVisibility(View.GONE);
                containerVideo.setVisibility(View.VISIBLE);
                helper.getView(R.id.iv_video_play).setOnClickListener(v -> {
                    ARouter.getInstance().build(ARouterUrlKt.VideoPlay)
                            .withString("videoUrl", item.getVideo())
                            .withString("coverUrl", item.getImages())
                            .withString("title", item.getDynamicContent())
                            //.withString(ExtraCons.EXTRA_KEY_VIDEO_DATA, new Gson().toJson(new DynamicCollection(getData())))
                            //.withInt("noteId", item.getId())
                            //.withString(ExtraCons.EXTRA_KEY_EDIT_MINE, PersonHomePageFragment.PERSON_HOME_PAGE_FRAGMENT)
                            .navigation(getContext());
                });
                //  addChildClickViewIds(R.id.iv_video_play);
            } else {
                //图文
                List<String> imageList = Arrays.asList(item.getImages().split(","));
                initGroupImageAdapter(imageList, containerImage);
                containerVideo.setVisibility(View.GONE);
                containerImage.setVisibility(View.VISIBLE);
            }
        }

        //    helper.init(getContext(), item.getCommentList());

    }

    public long getLastDynamicId() {
        if (getData().size() == 0) return 0;
        for (int i = getData().size() - 1; i >= 0; i--) {
            if (getData().get(i).getItemType() == HomeMultiItemEntity.HOME_DYNAMIC) {
                return getData().get(i).getDynamicResult().getId();
            }
        }
        return 0;
    }

    public int getDynamicPositionById(int dynamicId) {
        for (int i = 0; i < getData().size(); i++) {
            HomeMultiItemEntity entity = getItem(i);
            if (entity.getItemType() == HomeMultiItemEntity.HOME_DYNAMIC && entity.getDynamicResult().getId() == dynamicId) {
                return i;
            }
        }
        return -1;
    }

    public void postAttentionByUserId(int userId, boolean attention) {
        for (int i = 0; i < getData().size(); i++) {
            HomeMultiItemEntity entity = getItem(i);
            if (entity.getItemType() == HomeMultiItemEntity.HOME_DYNAMIC) {
                if (entity.getDynamicResult().getUserId() == userId) {
                    postAttention(i, attention);
                }
            } else if (entity.getItemType() == HomeMultiItemEntity.HOME_FRIEND_RECOMMEND) {
                if (attention) {
                    getFriendAdapter().postAttention(userId);
                }
            } else if (entity.getItemType() == HomeMultiItemEntity.HOME_FRIEND_RECOMMEND_BETA) {
                if (attention) {
                    getRecoFriendAdapter().postAttention(userId);
                }
            }
        }
    }


    public void postLike(boolean like, int position) {
        if (getItem(position).getItemType() != HomeMultiItemEntity.HOME_DYNAMIC) return;
        DynamicResult dynamicResult = getItem(position).getDynamicResult();
        dynamicResult.praise(like);
        int oldCount = dynamicResult.getThumbNum();
        if (like) {
            dynamicResult.setThumbNum(++oldCount);
        } else {
            if (oldCount > 0) {
                dynamicResult.setThumbNum(--oldCount);
            }
        }
        notifyItemChanged(position, "postLike");
    }

    public void postComment(int position, CommentResult result) {
        if (getItem(position).getItemType() != HomeMultiItemEntity.HOME_DYNAMIC) return;
        DynamicResult dynamicResult = getItem(position).getDynamicResult();
       /*  BaseViewHolder viewHolder = (BaseViewHolder) getRecyclerView().findViewHolderForAdapterPosition(position);
        if (viewHolder != null) {
            viewHolder.addComment(result);
        }*/
        int oldCount = dynamicResult.getCommentNum();
        dynamicResult.setCommentNum(++oldCount);
        notifyItemChanged(position, "postComment");
    }

    public void delComment(int position) {
        if (getItem(position).getItemType() != HomeMultiItemEntity.HOME_DYNAMIC) return;
        DynamicResult dynamicResult = getItem(position).getDynamicResult();
        int oldCount = dynamicResult.getCommentNum();
        dynamicResult.setCommentNum(--oldCount);
        notifyItemChanged(position, "postComment");
    }

    public void postAttention(int position, boolean attention) {
        try {
            if (getItem(position).getItemType() != HomeMultiItemEntity.HOME_DYNAMIC) return;
            DynamicResult dynamicResult = getItem(position).getDynamicResult();
            dynamicResult.attention(attention);
            notifyItemChanged(position, "postAttention");
        } catch (ArrayIndexOutOfBoundsException e) {
            LogUtils.e("数组越界");
        }
    }


    /**
     * @param imageList
     * @param mImageGroup
     */
    private void initGroupImageAdapter(List<String> imageList, NineGridView mImageGroup) {
        ArrayList<ImageInfo> imageInfo = new ArrayList<>();
        for (int i = 0; i < imageList.size(); i++) {
            ImageInfo info = new ImageInfo();
            info.setThumbnailUrl(imageList.get(i));
            info.setBigImageUrl(imageList.get(i));
            imageInfo.add(info);
        }
        //单张图片的大小
        NineGridIvAdapter mGridIvAdapter = new NineGridIvAdapter(getContext(), imageInfo);
        mImageGroup.setSingleImageSize(McaUtils.getScreenWidth(getContext()) / 2);
        mImageGroup.setAdapter(mGridIvAdapter);
    }

    private DynamicEvent mEvent;

    public void setOnDynamicEvent(DynamicEvent event) {
        mEvent = event;
    }

    public interface DynamicEvent {
        void onPostLike(int id, int position);

        void onPostCancelLike(int id, int position);

        void onAttention(int id, int position);

        void onAttentionById(int userId);

        void onComment(int id, int position);

        void onMoreEvent(int eventId, int eventPos, Object ext);

        void onRefreshFriend();

        void onActiveMore();

        void onDynamicContract(int position);
    }
}
